package cn.ywang.server;

import cn.ywang.model.RpcRequest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * 处理socket请求
 *
 * @Auther: BeatificWang
 * @Date: 2018/11/25 23:24
 */
public class ProcessorHandler implements Runnable {

	private Socket socket;

	// 服务端发布的服务
	private Object service;

	public ProcessorHandler(Socket socket, Object service) {
		this.socket = socket;
		this.service = service;
	}

	@Override
	public void run() {
		// 处理请求
		ObjectInputStream inputStream = null;
		ObjectOutputStream outputStream = null;
		try {
			// 获取客户端的输入流
			inputStream = new ObjectInputStream(this.socket.getInputStream());
			// 反序列化远程传输的对象
			RpcRequest rpcRequest = (RpcRequest) inputStream.readObject();
			// 调用本地方法
			Object o = this.invoke(rpcRequest);
			// 获取客户端的输出流
			outputStream = new ObjectOutputStream(this.socket.getOutputStream());
			outputStream.writeObject(o);
			outputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private Object invoke(RpcRequest rpcRequest) {
		Object result = null;
		Object[] args = rpcRequest.getArgs();
		Class<?>[] types = new Class[args.length];
		for (int i = 0; i < args.length; i++) {
			types[i] = args[i].getClass();
		}
		try {
			Method method = this.service.getClass().getMethod(rpcRequest.getMethodName(), types);
			result = method.invoke(this.service, args);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
